import { citys } from './citys';

const fs = require("fs")


let citysList = []
let edgeMap = [];// 指向

const main = async () => {
    // 城市节点列表
    for await (const iterator of citys) {
        let list = []
        try {
            const datain = await fs.readFileSync(`./data/${iterator.item_code}in.json`, {})
            console.log(`读取${iterator.item_name}in-${iterator.item_code}`)
            list = JSON.parse(datain.toString('utf-8')).data.list;
            const dataout = await fs.readFileSync(`./data/${iterator.item_code}in.json`, {})
            console.log(`读取${iterator.item_name}out-${iterator.item_code}`)
            list = [...list, JSON.parse(dataout.toString('utf-8')).data.list];
        } catch (error) {
            console.error(error)
        }

        for await (const l of list) {
            if (!citysList.includes(l.city_name)) {
                citysList.push(l.city_name)
            }
            // 判断是否存在
            const hasItemIndex = edgeMap.find(n => {
                const Source = citysList.findIndex(m => m == iterator.item_name);
                const Target = citysList.findIndex(m => m == l.city_name);
                return Source && Target && Source == n.Source && Target == n.Target
            })
            const Source = citysList.findIndex(m => m == iterator.item_name);
            const Target = citysList.findIndex(m => m == l.city_name);
            if (hasItemIndex > -1) {
                edgeMap[hasItemIndex].Weight = Number(edgeMap[hasItemIndex].Weight) + l.value || 0
            } else {
                edgeMap.push({
                    id: edgeMap.length,
                    Source: Source < 0 ? 0 : Source, 
                    Target: Target < 0 ? 0 : Target,
                    Weight: l.value || 0
                })
            }
        }
    }
    // 生成城市 csv
    let nodeCsv = "Id,Label,timeset\n";
    for (let index = 0; index < citysList.length; index++) {
        const c = citysList[index];
        nodeCsv += `${index},${c},\n`
    }
    await fs.writeFileSync(`./node.csv`, nodeCsv)
    // 生成指向
    let lineCsv = "Source,Target,Id,Label,timeset,Weight\n";
    for (let index = 0; index < edgeMap.length; index++) {
        const e = edgeMap[index];
        lineCsv += `${e.Source},${e.Target},${index}, , ,${e.Weight || 0}\n`
    }
    await fs.writeFileSync(`./lineCsv.csv`, lineCsv)


    // const data = await fs.readFileSync("./data/110000in.json", {})
    // var text = JSON.parse(data.toString('utf-8'))
    // console.log(text.data.list)
}





main()